#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "sockets.h"

unsigned int getSocket(int port)
{
  unsigned int         welcome_s;
  unsigned int         connect_s;
  struct sockaddr_in    server_addr;
  struct sockaddr_in    client_addr;
  int                   addr_len;

  welcome_s = socket(AF_INET, SOCK_STREAM, 0);

  server_addr.sin_addr.s_addr = htonl(INADDR_ANY);
  server_addr.sin_port = htons(port);
  bind(welcome_s, (struct sockaddr *)&server_addr, sizeof(server_addr));

  listen(welcome_s, 1);

  addr_len = sizeof(client_addr);

  connect_s = accept(welcome_s, (struct sockaddr *)&client_addr, &addr_len);

  close(welcome_s);

  return connect_s;
}

int SocSend(unsigned int socket, char *data)
{
  return send(socket, data, (strlen(data) + 1), 0);
}

char *SocReceive(unsigned int socket,int readSize)
{
  char in_buf[readSize];
  if (recv(socket,in_buf,sizeof(in_buf),0) == -1)
  {
    return NULL;
  }
  char *received;
  strcpy(received,in_buf);
  return received;
}

int SocClose(unsigned int socket)
{
  return close(socket);
}
